import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import Layout from "@/views/layout/layout.vue";
import addDynamicRoutes from '@/utils/addRoutes';

const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    name: 'Layout',
    component: Layout,
    meta: { check: true },
    redirect: '/home',
    children: [],
  },
  {
    path: '/login',
    name: 'login',
    meta: { check: false },
    component: () => import('../views/login/Login.vue')
  },
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
});


router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('wuyetoken');
  // console.log("token",JSON.parse(JSON.stringify(token)));
  const currentRoutes = router.getRoutes(); // 获取当前所有路由
  const layoutRoute = currentRoutes.find(item => item.name === 'Layout');
  // 如果用户未登录且访问需要认证的路由，则重定向到登录页面
  if (!token && to.meta.check) {
    next({ name: 'login' });
    return;
  }
  // 已登录且需要初始化路由
  if (token && layoutRoute && !layoutRoute.children.length) {
    const menus = JSON.parse(localStorage.getItem('wuyemenusJSON') || '[]');
    addDynamicRoutes(router, menus);
    next({ ...to, replace: true });
    return;
  }
  next();
});

export default router
